<template>
  <el-dialog
    draggable
    overflow
    :title="'过数'"
    v-model="visible"
    :width="700"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-tabs type="border-card">
      <el-tab-pane ref="tab" label="基础信息">
        <el-form
          :model="form"
          :rules="rules"
          ref="dialogForm"
          label-width="70px"
          label-position="right"
        >
          <el-row>
            <el-col v-if="showError != ''" :span="24">
              <el-alert type="error" show-icon>
                {{ showError }}
              </el-alert>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="返工？" prop="direction_id">
                    <el-switch
                      v-model="form.direction_id"
                      active-value="-1"
                      inactive-value="1"
                      active-text="是"
                      inactive-text="否"
                    ></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="数量" prop="quantity">
                    <el-input v-model="quantity" readonly class="readonly" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="加工车间" prop="pro_dept_id">
                    <skAutoChoose
                      v-model="form.pro_dept.name"
                      :name="'pro_dept'"
                      :asKey="'pro_dept_id'"
                      :disabled="!need_choose_dept"
                      :assign="form"
                      :params="{
                        'process_dept.process_id': processArray[form.direction_id]?.id,
                      }"
                      placeholder="有多个车间时，必须手动选择一个加工车间"
                      @select="proDeptSelect"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>

                <!-- <el-col :span="12">
                  <el-form-item label="加工厂" prop="outfactory_id">
                    <skAutoChoose
                      v-model="form.outfactory.name"
                      :params="[{ category_id: 111 }]"
                      :name="'factory'"
                      :assign="form"
                      :asKey="'outfactory_id'"
                      :disabled="!need_choose_factory"
                      @select="outfactorySelect"
                      placeholder="默认不外发"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收货部门" prop="location_id">
                    <skDicSelect
                      :code="'defaultLocation'"
                      v-model="form.location_id"
                      :editsource="'default'"
                    >
                    </skDicSelect>
                  </el-form-item>
                </el-col> -->
                <el-col :span="10">
                  <el-form-item label="上步工序">
                    <el-input
                      v-model="now_process_name"
                      readonly
                      class="readonly"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-form-item label="" label-width="30"
                    ><span style="color: red">》</span></el-form-item
                  ></el-col
                >
                <el-col :span="12">
                  <el-form-item label="过数流程" label-width="70">
                    <el-input v-model="process_name" readonly class="readonly"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="单据日期" prop="swiped_at">
                    <el-date-picker
                      v-model="form.swiped_at"
                      style="width: 100%"
                      type="datetime"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="默认当天"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="操作人" prop="swipor_id">
                    <skAutoChoose
                      v-model="form.swipor.name"
                      :name="'employee'"
                      :asKey="'swipor_id'"
                      :assign="form"
                      :params="getUserParams"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="A字架" prop="remark">
                    <el-input v-model="form.remark" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <sc-VxeTable
                ref="xGrid"
                :gridEvts="{}"
                :gridOps="{}"
                :tablecode="'pro_processes_pass_list'"
                :url="$API.pro.processes.pass_list"
                :order="'asc'"
                :sort="'swiped_at'"
                :params="getParams"
              >
              </sc-VxeTable>
            </el-col>
          </el-row>
          <sc-VxeTable
            ref="xGrid1"
            :gridEvts="gridEvents"
            :gridOps="gridOps"
            :data="form.details"
            :tablecode="'pro_pot_swipe'"
          >
          </sc-VxeTable>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script>
import tool from "@/utils/tool";
import skAutoChoose from "@/components/skAutoChoose";

import skDicSelect from "@/components/skDicSelect";
export default {
  emits: ["success", "closed"],
  components: { skAutoChoose, skDicSelect },
  data() {
    return {
      gridEvents: {},
      now_process_name: "",
      process_name: "",
      need_choose_dept: false,
      need_choose_factory: false,
      showError: "",
      gridOps: {
        height: 200,
        columns: [
          {
            field: "out_quantity",
            event: {
              keyup: ({ row }) => {
                row["rejects_quantity"] = this.quantity - row["out_quantity"];
                if (row["rejects_quantity"] < 0) {
                  row["out_quantity"] = this.quantity;
                  row["rejects_quantity"] = 0;
                }
                row.faultle_quantity = row.out_quantity;
              },
            },
          },
        ],
      },
      form: {
        swipor: {},
        pro_dept: {},
        outfactory: { name: "" },
        details: [],
        location_id: "",
        direction_id: "-1",
        outfactory_id: 31,
        swiped_at: tool.dateFormat(new Date()),
      },
      quantity: 0,
      rules: {
        direction_id: [{ required: true, message: "" }],
        swipor_id: [{ required: true, message: "操作人必填" }],
        swiped_at: [{ required: true, message: "操作时间必填" }],
      },
      visible: false,
      isSaveing: false,
      processArray: {
        "-1": {
          name: "不可用",
          id: 0,
          pro_dept: [],
        },
        1: {
          name: "不可用",
          id: 0,
          pro_dept: [],
        },
      },
    };
  },
  watch: {
    processArray: {
      handler() {
        this.form.direction_id = 1;
      },
      deep: true,
      immediate: true,
    },
    "form.direction_id": {
      handler(val) {
        this.process_name = this.processArray[val]?.name ?? "";
        this.need_choose_dept =
          this.processArray[val]?.pro_dept.length > 1 ? true : false;

        if (this.processArray[val]?.pro_dept.length > 1) {
          this.form.pro_dept_id = "";
          this.form.pro_dept = {};
        } else if (this.processArray[val]?.pro_dept.length == 1) {
          this.form.pro_dept_id = this.processArray[val]?.pro_dept[0].id;
          this.form.pro_dept = this.processArray[val]?.pro_dept[0];
        }

        this.need_choose_factory = this.processArray[val]?.allow_out == 1;
        if (this.need_choose_factory == false) {
          this.form.outfactory_id = 0;
          this.form.outfactory = { name: "" };
          this.form.location_id = 0;
        }
        this.rules.pro_dept_id = {
          required: this.need_choose_dept,
          message: this.processArray[val]?.name + "有多个加工车间，加工车间必选！",
        };
        this.rules.outfactory_id = {
          required: this.need_choose_factory,
          message: this.processArray[val]?.name + "允许外发，加工厂必选！",
        };
        this.rules.location_id = {
          required: this.need_choose_factory,
          message: this.processArray[val]?.name + "允许外发，收货部门必选！",
        };
      },
    },
  },
  methods: {
    //显示
    open() {
      this.visible = true;
      return this;
    },
    outfactorySelect(data) {
      if (data.id ?? 0 > 0) {
        this.form.pro_dept_id = 0;
        this.form.location_id = "";
        this.form.pro_dept = { name: "车间/加工厂只能选一个！" };
      }
    },
    getParams() {
      return { open_card_id: this.form.open_card_id };
    },
    proDeptSelect(data) {
      if (data.id ?? 0 > 0) {
        this.form.outfactory_id = 0;
        this.form.location_id = 0;
        this.form.outfactory = { name: "无需设置" };
      }
    },
    getUserParams() {
      return [{ "position.pro_process.name": this.process_name }];
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async valid => {
        if (this.form.details.length == 0) {
          return this.$message.error("在制品库存已入库！无法返工过数！");
        }
        if (valid) {
          this.isSaveing = true;
          var res = await this.$API.pro.processes.swipe.post(this.form);
          this.isSaveing = false;
          if (res.code == 200) {
            this.$emit("success", this.form);
            this.visible = false;
            this.$message.success("操作成功");
          }
        }
      });
    },

    async getProcess(id, out_process_id) {
      return await this.$API.pro.OpenCard.getRoute.get({ id: id }).then(res => {
        if (res.data != "")
          res.data.filter((v, k) => {
            if (v.process_id == out_process_id) {
              if (k != 0) this.processArray["-1"] = res.data[k - 1].process;
              if (k != res.data.length - 1)
                this.processArray["1"] = res.data[k + 1].process;
            }
          });
      });
    },
    //表单注入数据
    setData(data) {
      this.now_process_name = data.process.name;
      this.form.open_card_id = data.open_card_id;
      this.quantity = data.out_quantity = data.faultle_quantity;
      console.log(data);
      if (data.outfactory_id == 0) {
        this.getProcess(
          data.open_card_id,
          data.faultle_quantity > 0 ? data.process_id : 0
        );
        data.rejects_quantity = 0;
        this.form.details = [data];
      } else {
        this.showError = "外发库存不可过数！请从工序收货入库！";
      }

      return this;
    },
  },
};
</script>

<style></style>
